require 'Qt4'
require '/usr/share/hzvirt/hzvault_newvm'

class HZVaultMain < Qt::Widget
  slots 'new_vm()'
  slots 'start_vm()'
  slots 'modify_vm()'
  slots 'delete_vm()'
  slots 'reboot()'
  slots 'halt()'
  slots 'quit()'
  slots 'launch_vm(QListWidgetItem *)'
  def initialize(parent = nil)
    super
    showMaximized()
    setStyleSheet("HZVaultMain {background-color: black;} QPushButton {background-color: #101010; color: #7e7e7e;} QListWidget {background-color: #101010; color: #aeaeae;}")

    #separation en deux colonnes
    @lh = Qt::HBoxLayout.new(self)

    #colonne de gauche : visuel + boutons halt et reboot
    @lh_lv1 = Qt::VBoxLayout.new()
    @lh.addLayout(@lh_lv1)

    @tete2mort = Qt::Label.new()
    @tete2mort.setPixmap(Qt::Pixmap.new("/usr/share/hzvirt/head.png"))
    @lh_lv1.addWidget(@tete2mort)

    @lh_lv1_lh = Qt::HBoxLayout.new()
    @lh_lv1.addLayout(@lh_lv1_lh)
    @halt = Qt::PushButton.new(tr('Halt'), self)
    @lh_lv1_lh.addWidget(@halt)
    connect(@halt, SIGNAL('clicked()'), self, SLOT('halt()'))
    @restart = Qt::PushButton.new(tr('Reboot'), self)
    connect(@restart, SIGNAL('clicked()'), self, SLOT('reboot()'))
    @lh_lv1_lh.addWidget(@restart)
    Qt::Shortcut.new(Qt::KeySequence.new(Qt::CTRL.to_i + Qt::Key_Q.to_i), self, SLOT('quit()'));

    @lh.addSpacing(200)

    #colonne de gauche : text + liste des vms + actions
    @lh_lv2 = Qt::VBoxLayout.new()
    @lh.addLayout(@lh_lv2)

    #Liste des VMs
    @vms = Qt::ListWidget.new()
    @vms.setSelectionMode(Qt::AbstractItemView::SingleSelection)
    @list = IO.popen('VBoxManage list vms | grep -e "}$" | sed -e \'s/^"//\' | sed -e \'s/".*$//\'').readlines
    if(@list.empty?)
	    Qt::ListWidgetItem.new(tr("No virtual machines available for the moment"),@vms)
    else
	    @list.each {|vm| Qt::ListWidgetItem.new(vm,@vms)}
	    @vms.setCurrentRow(0)
	    connect(@vms, SIGNAL('itemDoubleClicked(QListWidgetItem *)'), self, SLOT('launch_vm(QListWidgetItem *)')) 
    end
    @lh_lv2.addWidget(@vms)

    #Boutons
    @lh_lv2_lh = Qt::HBoxLayout.new()
    @lh_lv2.addLayout(@lh_lv2_lh)

    @new_vm = Qt::PushButton.new(tr('New VM'), self)
    connect(@new_vm, SIGNAL('clicked()'),self, SLOT('new_vm()')) 
    @lh_lv2_lh.addWidget(@new_vm)

    @import_vm = Qt::PushButton.new(tr('Import VM'), self)
    #connect(@import_vm, SIGNAL('clicked()'),self, SLOT('new_vm()')) 
    @lh_lv2_lh.addWidget(@import_vm)

    @mod_vm = Qt::PushButton.new(tr('Modify VM'), self)
    @lh_lv2_lh.addWidget(@mod_vm)

    @delete_vm = Qt::PushButton.new(tr('Delete VM'), self)
    connect(@delete_vm, SIGNAL('clicked()'),self, SLOT('delete_vm()')) 
    @lh_lv2_lh.addWidget(@delete_vm)

    @start_vm = Qt::PushButton.new(tr('Start VM'), self)
    connect(@start_vm, SIGNAL('clicked()'),self, SLOT('start_vm()')) 
    @lh_lv2_lh.addWidget(@start_vm)

    @lh_lv2.addSpacing(200)

    @text = Qt::Label.new()
    @text.setPixmap(Qt::Pixmap.new("/usr/share/hzvirt/text.png"))
    @lh_lv2.addWidget(@text)
    
  end

  def new_vm
	  $widget2 = HZVaultNewVM.new()
	  $widget2.show()
  end

  def start_vm()
	  launch_vm(@vms.selectedItems()[0])
  end

  def delete_vm()
	  #TODO lister et virer le dd virtuel
	  #TODO popup de confirmation
	  
	  system('VBoxManage controlvm "' + @vms.selectedItems()[0].text.gsub(/\n/,"") + '" poweroff')
	  system('VBoxManage modifyvm "' + @vms.selectedItems()[0].text.gsub(/\n/,"") + '" --dvd none')
#	  @hda_vmdk = IO.popen('VBoxManage showvminfo "' + @vms.selectedItems()[0].text.gsub(/\n/,"") + '" | grep vmdk | sed -e "s/^.*:\s*//" | sed -e "s/vmdk.*$/vmdk/"').readlines()[0].gsub(/\n/,"")
#	  @hda_dir = IO.popen('dirname "' + @hda_vmdk + '"').readlines()[0].gsub(/\n/,"")
#	  @hda_vmdks = IO.popen('cat "' + @hda_vmdk + '" | grep SPARSE | cut -d " " -f 4').readlines()
	  @hda_uuid = IO.popen('VBoxManage showvminfo "' + @vms.selectedItems()[0].text.gsub(/\n/,"") + '" | grep vmdk | sed -e "s/^.*UUID:\s*//" | sed -e "s/).*$//"').readlines()[0].gsub(/\n/,"")
 	  system('VBoxManage storageattach "' + @vms.selectedItems()[0].text.gsub(/\n/,"")  + '" --storagectl "Disk Controller" --port 0 --device 0 --medium none')
 	  system('VBoxManage storageattach "' + @vms.selectedItems()[0].text.gsub(/\n/,"")  + '" --storagectl "Disk Controller" --port 1 --device 0 --medium none')
#	  system('VBoxManage modifyvm "' + @vms.selectedItems()[0].text.gsub(/\n/,"") + '" --hda none')
	  system('VBoxManage closemedium disk "' + @hda_uuid + '" --delete')
#	  system('rm -f "' + @hda_vmdk + '"')
#	  @hda_vmdks.each { |vmdk| system('rm -f "' + @hda_dir + vmdk.gsub(/\n/,"").gsub(/\"/,"") + '"')}
#	  @hda_vmdks.each { |vmdk| puts('rm -f "' + @hda_dir + "/" +  vmdk.gsub(/\n/,"").gsub(/\"/,"") + '"')}
	  system('VBoxManage unregistervm "' + @vms.selectedItems()[0].text.gsub(/\n/,"") + '" --delete') { |r| puts r.gets }
	  refresh
  end

  def launch_vm(vm)
	  #todo memory not working (???? changement de spec dasn VBoxManage ?)
	  IO.popen('VBoxManage modifyvm "' + vm.text.gsub(/\n/,"") + '" --memory ' +  ((`cat /proc/meminfo | grep MemTotal | sed -e "s/\s\s*/ /" | cut -d " " -f 2`.to_i/1024)-256).to_s)
	  @cdrom=IO.popen('VBoxManage list hostdvds | grep -e "^Name:" | cut -d ":" -f 2 | sed -e "s/\s*//g"').readlines()[0]
	  if(!@cdrom.empty?)
		  puts "DVD detected : '" + @cdrom.gsub(/\n/,"") + "'"
		  IO.popen('VBoxManage storageattach "' + vm.text.gsub(/\n/,"") + '" --storagectl "Disk Controller" --port 1 --device 0 --type dvddrive --medium host:"' + @cdrom.gsub(/\n/,"") + '"') { |f| f.each { |g| puts g}}
		  #IO.popen('VBoxManage modifyvm "' + vm.text.gsub(/\n/,"") + '" --boot1 dvd --boot2 disk')
		  #puts('VBoxManage modifyvm "' + vm.text.gsub(/\n/,"") + '" --boot1 dvd --boot2 disk')
		  sleep(1)
		  IO.popen('VBoxManage showvminfo "' + vm.text.gsub(/\n/,"") + '"') { |f| puts f.gets }
	  end
	  system('VBoxManage setextradata global "GUI/SuppressMessages" "remindAboutInputCapture,remindAboutMouseIntegrationOn,remindAboutGoingFullscreen,remindAboutAutoCapture,remindAboutconfirmGoingFullscreen,remindAboutInaccessibleMedia,confirmInputCapture,showRuntimeError.warning.NoDNSforNAT,showRuntimeError.warning.HostAudioNotResponding,confirmGoingFullscreen"')
	  sleep(1)
	  IO.popen('VBoxManage showvminfo "' + vm.text.gsub(/\n/,"") + '"') { |f| puts f.gets }
	  system('VirtualBox --startvm "' + vm.text.gsub(/\n/,"") + '" --type gui')
  end
  def refresh()
	  until @vms.count == 0
		  @vms.takeItem(0)
	  end
	  @list = IO.popen('VBoxManage list vms | grep -e "}$" | sed -e \'s/^"//\' | sed -e \'s/".*$//\'').readlines
	  if(@list.empty?)
		  Qt::ListWidgetItem.new(tr("No virtual machines available for the moment"),@vms)
	  else
		  @list.each {|vm| Qt::ListWidgetItem.new(vm,@vms)}
		  @vms.setCurrentRow(0)
		  connect(@vms, SIGNAL('itemDoubleClicked(QListWidgetItem *)'), self, SLOT('launch_vm(QListWidgetItem *)'))
	  end
  end
  def reboot()
	exec("shutdown -r now")
  end
  def halt()
	exec("shutdown -h now")
  end
  def quit()
        print "toto"
	Process.exit
  end
end
